//
//  BaseRequestModel.m
//  Community
//
//  Created by andy on 14-6-17.
//  Copyright (c) 2014年 HangZhou PiaoYoung Co.Ltd. All rights reserved.
//
#import "RequestOperationManager.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation RequestOperationManager

static RequestOperationManager * manager = nil;

+ (void)startWithBaseURL:(NSString *)baseURL{
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        NSString *URLStr = baseURL;
        NSURL *url = [[NSURL alloc] initWithString:URLStr];
        
        manager = [[RequestOperationManager alloc] initWithBaseURL:url];
        
        [self setVersionEnable:NO];
        
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                             @"application/json",
                                                             @"text/json",
                                                             @"text/javascript",
                                                             @"text/plain",
                                                             @"text/html", nil];
    });
}

+(void)setVersionEnable:(BOOL)enableVersion{
    if(enableVersion){
        NSString *versionNumber = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
        [[RequestOperationManager defaultManager].requestSerializer setValue:versionNumber forHTTPHeaderField:@"version"];
    }
}

+ (instancetype)defaultManager {
    NSParameterAssert(manager);
    return manager;
}

- (void)successOperation:(NSDictionary *)responseObject analyse:(AnalyseBlock)analyse error:(void (^)(PYError *))error complete:(void (^)(PYResult *))complete {
    NSDictionary *dictionary = transfer(responseObject);
    NSLog(@"response is dictionary = %@", dictionary);
    PYResult *result = [[PYResult alloc] init];
    [result anasyleData:dictionary];
    if (result.codeStyle == 1) {
        if (analyse) {
            result = analyse(dictionary);
            [result anasyleData:dictionary];
        }
        if (complete) {complete(result);}
    } else {
        PYError *e = [PYError errorWithCode:result.codeStyle message:result.message];
        if (error) {error(e);}
    }
}

- (void)failureOperation:(void (^)(PYError *))error err:(NSError *)err {
    if (err) {
        NSLog(@"response error is dictionary = %@", err.localizedDescription);
        PYError *e = [PYError networkError];
        e.error = err;
        if (error != nil) {
            error(e);
        }
    }
}

- (AFHTTPRequestOperation *)get:(NSString *)url params:(NSDictionary *)params complete:(void (^)(PYResult *))complete error:(void (^)(PYError *))error analyBlock:(AnalyseBlock)analyse {
    
    NSLog(@"request method : get  url:%@", url);
    NSLog(@"params is %@", params);
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    
    return [[RequestOperationManager defaultManager] GET:url parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"request url is %@", operation.request.URL);
        [self successOperation:responseObject analyse:analyse error:error complete:complete];
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull err) {
        NSLog(@"request url is %@", operation.request.URL);
        [self failureOperation:error err:err];
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    }];
}

- (AFHTTPRequestOperation *)post:(NSString *)url params:(NSDictionary *)params complete:(void (^)(PYResult *))complete error:(void (^)(PYError *))error analyBlock:(AnalyseBlock)analyse {
    
    NSLog(@"request method : get  url:%@", url);
    NSLog(@"params is %@", params);
    
    [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    return [[RequestOperationManager defaultManager] POST:url parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"rrequest url is %@", operation.request.URL);
        
        [self successOperation:responseObject analyse:analyse error:error complete:complete];
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull err) {
        NSLog(@"rrequest url is %@", operation.request.URL);
        [self failureOperation:error err:err];
        [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
        
    }];
}

+ (AFHTTPRequestOperation *)post:(NSString *)url params:(NSDictionary *)params complete:(void (^)(PYResult *))complete error:(void (^)(PYError *))error analyBlock:(AnalyseBlock)analyse {
    return [[RequestOperationManager defaultManager] post:url params:params complete:complete error:error analyBlock:analyse];
}

+ (AFHTTPRequestOperation *)get:(NSString *)url params:(NSDictionary *)params complete:(void (^)(PYResult *))complete error:(void (^)(PYError *))error analyBlock:(AnalyseBlock)analyse {
    return [[RequestOperationManager defaultManager] get:url params:params complete:complete error:error analyBlock:analyse];
}


NSDictionary *transfer(NSDictionary *originDictionary) {
    NSMutableDictionary *currentDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    currentDictionary[@"code"] = originDictionary[@"code"];
    currentDictionary[@"message"] = originDictionary[@"message"];
    
    NSObject * object = originDictionary[@"data"];
    
    if ([object isKindOfClass:[NSDictionary class]]) {
        currentDictionary[@"data"] = lowperCaseWithDictionary((NSDictionary*)object);
    }
    if ([object isKindOfClass:[NSArray class]]) {
        currentDictionary[@"data"] = lowerCaseWithArray((NSArray *)object);
    }
    if ([object isKindOfClass:[NSString class]]) {
        currentDictionary[@"data"] = lowerCaseWithString((NSString *)object);
    }
    return currentDictionary;
}

NSString *lowerCaseWithString(NSString *string) {
    if ([string isKindOfClass:[NSNull class]]) {
        return @"";
    }
    return string;
}

NSArray *lowerCaseWithArray(NSArray *array) {
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSObject * subObject in array) {
        if ([subObject isKindOfClass:[NSDictionary class]]) {
            [mutableArray addObject:lowperCaseWithDictionary((NSDictionary *)subObject)];
        }
        if([subObject isKindOfClass:[NSString class]]){
            [mutableArray addObject:lowerCaseWithString((NSString *)subObject)];
        }
        if([subObject isKindOfClass:[NSArray class]]){
            [mutableArray addObject:lowerCaseWithArray((NSArray *)subObject)];
        }
    }
    return mutableArray;
}

NSDictionary *lowperCaseWithDictionary(NSDictionary *dictionary) {
    dictionary = unUsedKeyFilter(dictionary);
    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
    for (NSString *key in dictionary.allKeys) {
        NSObject * object = dictionary[key];
        if ([object isKindOfClass:[NSDictionary class]]) {
            mutableDictionary[key.lowercaseString] = lowperCaseWithDictionary((NSDictionary *)object);
        } else if ([object isKindOfClass:[NSArray class]]) {
            mutableDictionary[key.lowercaseString] = lowerCaseWithArray((NSArray *)object);
        } else {
            mutableDictionary[key.lowercaseString] = lowerCaseWithString((NSString *)object);
        }
    }
    return mutableDictionary;
}


NSDictionary *unUsedKeyFilter(NSDictionary *dictionary) {
    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] initWithDictionary:dictionary];
    NSArray *filterKeys = @[@"MODIFY_USER", @"STATUS", @"REMARK", @"CREATE_USER", @"MODIFY_TIME", @"USE_FLAG", @"LOGIN_CODE"];
    [mutableDictionary removeObjectsForKeys:filterKeys];
    return mutableDictionary;
}
@end
